<?php

class newsController extends baseController {
	
	public function index() {
		$limit_news_per_page = 5;
		
		$news = new News ();
		
		$count_news = $news->getCountNews();
		$last_page = ceil($count_news/$limit_news_per_page);
		
		$curent_page =$this->registry->router->getParam( 'page' );
		 
		if ( $curent_page<1) {
			$curent_page = 1;
		}elseif ($curent_page>$last_page){
			$curent_page = $last_page;
		}
		
		$max_page = ($curent_page-1)*$limit_news_per_page;
		$this->registry->template->news = $news->getNews ( $max_page, $limit_news_per_page );
		
		$this->registry->template->last_page = $last_page;
		$this->registry->template->current_page = $curent_page;
		
		
	}
	
	public function view() {
		
		$news = new News ();
		
		$news_id = $this->registry->router->getParam ( 'id' );
		$this->registry->template->news_item = $news->getNewsId ( $news_id );
		$this->registry->template->news_comments = $news->getComments ( $news_id );

		$user_for_comment = new User();
		$this->registry->template->user_for_comment = $user_for_comment;
	}
	
	public function comment() {
		$news = new News ();
		
		//only authorized user can add comment
		if (Auth::getInstanse ()) {
			if ($this->registry->router->getPostValue ( 'submit' )) {
				$comment = $this->registry->router->getPostValue ( 'comment' );
				$user_id = Auth::getAuthUserId ();
				$news_id = $this->registry->router->getParam ( 'id' );
				
				$news->commentAdd ( $comment, $user_id, $news_id );
				
				//TODO create in AJAX addition
				$this->registry->router->redirect("news","view",array("id"=>$news_id));				
			}
		}
	
	}
	
	public function add(){
		if ($this->registry->router->getPostValue ( 'submit' )){
			$user = Auth::getInstanse ();
			if ($user && ($user['role']=='admin' || $user['role']='publisher')){
				$news = new News();
				
				$text_preview = $this->registry->router->getPostValue ( 'text_preview' );
				$text = $this->registry->router->getPostValue ( 'text' );
				$title = $this->registry->router->getPostValue ( 'title' );
				
				$news->addNews($text_preview, $text, $title);
				
				$this->registry->template->message = "New news was added";
			}	 
			
		}
	}

}
?>
